using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Windows.Input;

namespace WPF_MVVM_Test.MVVM_ViewModel.WorkOrderTask
{
    /// <summary>
    /// 人员选择弹窗ViewModel
    /// </summary>
    public class EmployeeSelectionViewModel : INotifyPropertyChanged
    {
        #region 私有字段
        private string _searchKeyword;
        private ObservableCollection<EmployeeItem> _allEmployees;
        private ObservableCollection<EmployeeItem> _filteredEmployees;
        private ObservableCollection<EmployeeItem> _selectedEmployees;
        #endregion

        #region 公共属性
        public string SearchKeyword
        {
            get => _searchKeyword;
            set
            {
                _searchKeyword = value;
                OnPropertyChanged();
                FilterEmployees();
            }
        }

        public ObservableCollection<EmployeeItem> AllEmployees
        {
            get => _allEmployees;
            set
            {
                _allEmployees = value;
                OnPropertyChanged();
            }
        }

        public ObservableCollection<EmployeeItem> FilteredEmployees
        {
            get => _filteredEmployees;
            set
            {
                _filteredEmployees = value;
                OnPropertyChanged();
            }
        }

        public ObservableCollection<EmployeeItem> SelectedEmployees
        {
            get => _selectedEmployees;
            set
            {
                _selectedEmployees = value;
                OnPropertyChanged();
                OnPropertyChanged(nameof(SelectedCount));
            }
        }

        public int SelectedCount => SelectedEmployees?.Count ?? 0;

        public string SelectedCountText => $"已选对象 {SelectedCount}";
        #endregion

        #region 命令
        public ICommand SearchCommand { get; private set; }
        public ICommand ClearAllCommand { get; private set; }
        public ICommand ConfirmCommand { get; private set; }
        public ICommand CancelCommand { get; private set; }
        public ICommand RemoveSelectedCommand { get; private set; }
        #endregion

        #region 事件
        public event Action<bool> RequestClose;
        public event PropertyChangedEventHandler PropertyChanged;
        #endregion

        #region 构造函数
        public EmployeeSelectionViewModel()
        {
            InitializeData();
            InitializeCommands();
        }
        #endregion

        #region 私有方法
        private void InitializeData()
        {
            // 初始化模拟员工数据
            AllEmployees = new ObservableCollection<EmployeeItem>
            {
                new EmployeeItem { Id = "001", Name = "堂灵波", IsSelected = false },
                new EmployeeItem { Id = "002", Name = "池雅丽", IsSelected = false },
                new EmployeeItem { Id = "003", Name = "童芳洁", IsSelected = false },
                new EmployeeItem { Id = "004", Name = "吕新之", IsSelected = false },
                new EmployeeItem { Id = "005", Name = "禾和照", IsSelected = false },
                new EmployeeItem { Id = "006", Name = "通湘云", IsSelected = false },
                new EmployeeItem { Id = "007", Name = "司空倩", IsSelected = false },
                new EmployeeItem { Id = "008", Name = "张三", IsSelected = false },
                new EmployeeItem { Id = "009", Name = "李四", IsSelected = false },
                new EmployeeItem { Id = "010", Name = "王五", IsSelected = false },
                new EmployeeItem { Id = "011", Name = "赵六", IsSelected = false },
                new EmployeeItem { Id = "012", Name = "钱七", IsSelected = false },
                new EmployeeItem { Id = "013", Name = "孙八", IsSelected = false },
                new EmployeeItem { Id = "014", Name = "周九", IsSelected = false },
                new EmployeeItem { Id = "015", Name = "吴十", IsSelected = false }
            };

            // 为每个员工项订阅选择状态变化事件
            foreach (var employee in AllEmployees)
            {
                employee.PropertyChanged += Employee_PropertyChanged;
            }

            FilteredEmployees = new ObservableCollection<EmployeeItem>(AllEmployees);
            SelectedEmployees = new ObservableCollection<EmployeeItem>();
        }

        private void Employee_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == nameof(EmployeeItem.IsSelected) && sender is EmployeeItem employee)
            {
                if (employee.IsSelected)
                {
                    if (!SelectedEmployees.Contains(employee))
                    {
                        SelectedEmployees.Add(employee);
                    }
                }
                else
                {
                    SelectedEmployees.Remove(employee);
                }
                OnPropertyChanged(nameof(SelectedCount));
                OnPropertyChanged(nameof(SelectedCountText));
            }
        }

        private void InitializeCommands()
        {
            SearchCommand = new RelayCommand(FilterEmployees);
            ClearAllCommand = new RelayCommand(ClearAllSelected);
            ConfirmCommand = new RelayCommand(() =>
            {
                System.Diagnostics.Debug.WriteLine($"ConfirmCommand executed, SelectedEmployees count: {SelectedEmployees?.Count ?? 0}");
                RequestClose?.Invoke(true);
            });
            CancelCommand = new RelayCommand(() => RequestClose?.Invoke(false));
            RemoveSelectedCommand = new RelayCommand<EmployeeItem>(RemoveSelected);
        }

        private void FilterEmployees()
        {
            if (string.IsNullOrWhiteSpace(SearchKeyword))
            {
                FilteredEmployees.Clear();
                foreach (var employee in AllEmployees)
                {
                    FilteredEmployees.Add(employee);
                }
            }
            else
            {
                var filtered = AllEmployees.Where(e => e.Name.Contains(SearchKeyword)).ToList();
                FilteredEmployees.Clear();
                foreach (var employee in filtered)
                {
                    FilteredEmployees.Add(employee);
                }
            }
        }

        private void ClearAllSelected()
        {
            foreach (var employee in AllEmployees)
            {
                employee.IsSelected = false;
            }
            SelectedEmployees.Clear();
            OnPropertyChanged(nameof(SelectedCount));
            OnPropertyChanged(nameof(SelectedCountText));
        }

        private void RemoveSelected(EmployeeItem employee)
        {
            if (employee != null)
            {
                employee.IsSelected = false;
            }
        }

        protected virtual void OnPropertyChanged([System.Runtime.CompilerServices.CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        #endregion
    }

    /// <summary>
    /// 员工项模型
    /// </summary>
    public class EmployeeItem : INotifyPropertyChanged
    {
        private bool _isSelected;

        public string Id { get; set; }
        public string Name { get; set; }

        public bool IsSelected
        {
            get => _isSelected;
            set
            {
                _isSelected = value;
                OnPropertyChanged();
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([System.Runtime.CompilerServices.CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
